<?php

namespace App\Http\Middleware;

use Closure;
use Dingo\Api\Routing\Helpers;

class IpVerify
{
    use Helpers;

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $ip = $request->getClientIp();
        $middleware = \request()->route()->middleware();
        if (array_search('web', $middleware) && array_search('auth', $middleware)) {
            $user = \Auth::user();
            $backendIps = $user->backend_ips;
            if (!in_array($ip, $backendIps)) {
                return $this->response->error('非法IP', 503);
            }
        }

        if (array_search('api.controller', $middleware)) {
            $user = \Auth::user();
            $apiIps = $user->api_ips;
            if (!in_array($ip, $apiIps)) {
                return $this->response->error('非法IP', 503);
            }
        }

        return $next($request);
    }
}
